import request from '@/utils/request'
import SparkMD5 from "spark-md5";


class Filebase {
    constructor() {
    }
    async createMultipart(md5,namespace) {
        let url = `/filebase/api/v1/${namespace}/multiparts?appId=test`
        let res = await request.post(url, { digest: md5 },{timeout: 1200000})
        return res
    }
    async upload(file, uploadProgress,namespace,parentId) {
        let chunkSize = 10240000
        let md5 = await GetMD5(file, chunkSize)
        let upload = await this.createMultipart(md5,namespace)
        let chunks = Math.ceil(file.size / chunkSize);
        let currentChunk = 0;
        let percent = 0;
        let config = {
            onUploadProgress: event => {
                file.percent = percent + event.loaded/event.total*100/chunks
                if (uploadProgress){
                    console.log(file.percent)
                    uploadProgress(file)
                }
            },
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        };
        while (currentChunk < chunks) {
            let start = currentChunk * chunkSize
            let end = start + chunkSize
            if (end > file.size) {
                end = file.size
            }
            let spark = new SparkMD5.ArrayBuffer();
            let chunk = file.slice(start, end)
            let chunkArr =  await convArr(chunk)
            spark.append(chunkArr)
            let partmd5 = spark.end()
            spark.destroy()
            let formData = new FormData();
            formData.append('file',chunk,currentChunk)
            await request.post(`/filebase/api/v1/${namespace}/multiparts/${upload.data.uploadId}/${currentChunk}?md5=${partmd5}&appId=test`, formData,config)
            currentChunk++
            percent = currentChunk *100 / chunks 
        }
        let param = {
            name: file.name,
            size: file.size,
            parent:parentId,
            kind: 'file',
        }
        console.log(parentId,namespace)
        let res = await request.put(`/filebase/api/v1/${namespace}/multiparts/${upload.data.uploadId}?appId=test`, param)
        return res
    }
}

let filebase = new Filebase()
export default filebase


function convArr(blob){
    return new Promise((resolve, reject) => {
        var reader = new FileReader();
        reader.onload = function() 
        {
            resolve(this.result)
        }
        reader.readAsArrayBuffer(blob);
    })
}

function GetMD5(file, chunkSize) {
    return new Promise((resolve, reject) => {
        let blobSlice =
            File.prototype.slice ||
            File.prototype.mozSlice ||
            File.prototype.webkitSlice;
        let chunks = Math.ceil(file.size / chunkSize);
        let currentChunk = 0;
        let spark = new SparkMD5.ArrayBuffer(); //追加数组缓冲区。
        let fileReader = new FileReader(); //读取文件
        fileReader.onload = function (e) {
            spark.append(e.target.result);
            currentChunk++;
            if (currentChunk < chunks) {
                loadNext();
            } else {
                var md5v = spark.end(); //完成md5的计算，返回十六进制结果。
                resolve(md5v);
            }
        };

        fileReader.onerror = function (e) {
            reject(e);
        };

        function loadNext() {
            let start = currentChunk * chunkSize;
            let end = start + chunkSize;
            (end > file.size) && (end = file.size);
            fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
        }
        loadNext();
    });
}